<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="项目标段" prop="institutionCode">
        <el-select
          filterable
          v-model="queryParams.institutionCode"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleBidChange"
        >
          <el-option-group
            v-for="group in projectBidOptions"
            :key="group.name"
            :label="group.name">
            <el-option
              v-for="item in group.bids"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>

      <el-form-item label="清单模板" prop="templateCode">
        <el-select
          v-model="queryParams.templateCode"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleTemplateChange"
        >
          <el-option
            v-for="item in templateOptions"
            :key="item.templateCode"
            :value="item.templateCode"
            :label="item.templateName"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="清单类型" prop="boqType">
        <el-select
          v-model="queryParams.boqType"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleBoqTypeChange"
        >
          <el-option
            v-for="dict in dict.type.supervisor_boq_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['agency:boq:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['agency:boq:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['agency:boq:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleSync"
          v-hasPermi="['agency:boq:add']"
        >同步</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="boqList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="清单编码" align="left" prop="boqCode" />
      <el-table-column label="清单名称" align="left" prop="boqName" width="200" show-overflow-tooltip />
      <el-table-column label="上级编号" align="center" prop="parentCode" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="折旧费" align="center" prop="depreciationTotal" />
      <el-table-column label="人数" align="center" prop="personAmount" />
      <el-table-column label="总期数" align="center" prop="periodAmount" />
      <el-table-column label="金额" align="center" prop="total" />
      <el-table-column label="显示排序" align="center" prop="orderNum" />
      <el-table-column label="叶节点" align="center" prop="leafNode" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.leafNode"/>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改监理清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="清单编码" prop="boqCode">
          <el-input v-model="form.boqCode" placeholder="请输入清单编码" />
        </el-form-item>
        <el-form-item label="清单名称" prop="boqName">
          <el-input v-model="form.boqName" placeholder="请输入清单名称" />
        </el-form-item>
        <el-form-item label="上级清单" prop="parentCode">
          <treeselect v-model="form.parentCode" :options="treeOptions" :normalizer="normalizer" placeholder="选择上级清单" noOptionsText="暂无数据" noResultsText="未搜索到匹配项" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" type="number" @input="calTotal" @keydown.native="handleKey" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="总期数" prop="periodAmount">
          <el-input v-model="form.periodAmount" type="number" @input="calTotal" @keydown.native="handleKey" placeholder="请输入期数" />
        </el-form-item>
        <el-form-item label="数量" prop="personAmount">
          <el-input v-model="form.personAmount" type="number" :disabled="personAmountFlag" @input="personAmountInput" @keydown.native="handleKey1" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="折旧费" prop="depreciationTotal">
          <el-input v-model="form.depreciationTotal" type="number" :disabled="depreciationTotalFlag" @input="depreciationTotalInput" @keydown.native="handleKey" placeholder="请输入折旧费" />
        </el-form-item>
        <el-form-item label="金额" prop="total">
          <el-input v-model="form.total" type="number" @keydown.native="handleKey" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBoq, getBoq, delBoq, addBoq, updateBoq, syncBoq, getTreeList, getTreeListExcludeChild } from "@/api/agency/boq";
import { selectProjectAgencyBid } from "@/api/project/bid";
import { dropdownList } from "@/api/agency/template";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as math from "mathjs";

export default {
  name: "Boq",
  dicts: ['sys_yes_no', 'supervisor_boq_type'],
  components: { Treeselect },
  data() {
    return {
      // 项目标段分组下拉框
      projectBidOptions: [],
      // 清单模板下拉框
      templateOptions: [],
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代建清单表格数据
      boqList: [],
      // 清单树选项
      treeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        institutionCode: null,
        templateCode: "1",
        boqType: "1"
      },
      // 表单参数
      form: {},
      depreciationTotalFlag: false,
      personAmountFlag: false,
      // 表单校验
      rules: {
        boqCode: [
          { pattern: /(^[1-9][0-9]+)|(^[1-9][0-9]*(-\w+)+)/, message: "清单编码格式不正确", trigger: "blur" },
          { required: true, message: "清单编码不能为空", trigger: "blur" }
        ],
        boqName: [
          { required: true, message: "清单名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.initBidSelect();
  },
  methods: {
    /** 初始化标段下拉框 */
    initBidSelect() {
      selectProjectAgencyBid().then(response => {
        this.projectBidOptions = response.data;
        if (this.projectBidOptions.length > 0) {
          this.queryParams.institutionCode = this.projectBidOptions[0].bids[0].code;
          this.getList();
          this.getTemplateList();
        }
      });
    },
    // 标段下拉框发生变化
    handleBidChange() {
      this.queryParams.pageNum = 1;
      this.queryParams.templateCode = "1";
      this.queryParams.boqType = "1";
      this.getList();
      this.getTemplateList();
    },
    // 模板下拉框发生变化
    handleTemplateChange() {
      this.queryParams.pageNum = 1;
      this.queryParams.boqType = "1";
      this.getList();
    },
    // 清单类型下拉框发生变化
    handleBoqTypeChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询代建清单列表 */
    getList() {
      this.loading = true;
      listBoq(this.queryParams).then(response => {
        this.boqList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询清单模板下拉框
    getTemplateList() {
      dropdownList({institutionCode: this.queryParams.institutionCode}).then(response => {
        this.templateOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        institutionCode: null,
        templateCode: null,
        boqType: null,
        institutionBoqCode: null,
        boqCode: null,
        boqName: null,
        parentCode: null,
        ancestors: null,
        orderNum: null,
        level: null,
        leafNode: null,
        unit: null,
        depreciationTotal: null,
        personAmount: null,
        periodAmount: null,
        amount: null,
        price: null,
        total: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 同步按钮操作
    handleSync() {
      this.$modal.confirm('同步功能将会删除原有数据，确定执行该操作？').then(() => {
        return syncBoq({institutionCode: this.queryParams.institutionCode, templateCode: this.queryParams.templateCode, boqType: this.queryParams.boqType});
      }).then(() => {
        this.$modal.msgSuccess("操作成功");
        this.getList();
      }).catch(() => {});
    },
    /** 转换清单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.boqCode,
        label: node.boqName,
        children: node.children
      };
    },
    /** 查询清单下拉树结构 */
    getTreeSelect() {
      getTreeList({institutionCode: this.queryParams.institutionCode,
        templateCode: this.queryParams.templateCode,
        boqType: this.queryParams.boqType}).then(response => {
        this.treeOptions = this.handleTree(response.data, "boqCode", "parentCode");
      });
    },
    getTreeSelectExcludeChild(row) {
      const id = row.id || this.ids[0];
      getTreeListExcludeChild({institutionCode: this.queryParams.institutionCode,
        templateCode: this.queryParams.templateCode,
        boqType: this.queryParams.boqType, id: id}).then(response => {
        this.treeOptions = this.handleTree(response.data, "boqCode", "parentCode");
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeSelect();
      this.open = true;
      this.title = "添加实验室清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeSelectExcludeChild(row);
      const id = row.id || this.ids
      getBoq(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改实验室清单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBoq(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.institutionCode = this.queryParams.institutionCode;
            this.form.templateCode = this.queryParams.templateCode;
            this.form.boqType = this.queryParams.boqType;
            addBoq(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的数据项？').then(function() {
        return delBoq(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    // 人数input事件
    personAmountInput() {
      if (this.form.personAmount != '') {
        this.depreciationTotalFlag = true;
        if (this.form.price != '' && this.form.periodAmount != '') {
          // 计算金额
          this.form.total = math.round(this.form.personAmount * this.form.periodAmount * this.form.price, 6);
        }
      } else {
        this.depreciationTotalFlag = false;
        this.form.total = null;
      }
    },
    // 折旧费input事件
    depreciationTotalInput() {
      console.log(this.form.depreciationTotal);
      if (this.form.depreciationTotal != '') {
        this.personAmountFlag = true;
        if (this.form.periodAmount != '') {
          this.form.total = math.round(this.form.depreciationTotal * this.form.periodAmount, 6) + math.round(this.form.price * this.form.periodAmount, 6);
        }
      } else {
        this.personAmountFlag = false;
        if (this.form.periodAmount == '' || this.form.price == '') {
          this.form.total = null;
        }
      }
    },
    calTotal() {
      if (this.personAmountFlag && !this.depreciationTotalFlag) {
        if (this.form.periodAmount != '' && this.form.periodAmount != '') {
          this.form.total = math.round(this.form.personAmount * this.form.periodAmount * this.form.price, 6);
        } else {
          this.form.total = null;
        }
      } else {
        if (this.form.periodAmount != '') {
          this.form.total = math.round(math.round(this.form.depreciationTotal * this.form.periodAmount, 6) + math.round(this.form.price * this.form.periodAmount, 6), 6);
        } else {
          if (this.form.periodAmount == '' || this.form.price == '') {
            this.form.total = null;
          }
        }
      }
    },
    handleKey(e) {
      let key = e.key
      // 不允许输入'e'和'.'
      if (key === 'e') {
        e.returnValue = false
        return false
      }
      return true
    },
    handleKey1(e) {
      let key = e.key
      // 不允许输入'e'和'.'
      if (key === 'e' || key === '.') {
        e.returnValue = false
        return false
      }
      return true
    }
  }
};
</script>

<style lang="scss">
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
</style>
